//
//  YWMaterialApplyDetailTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWMaterialApplyDetailTableViewController.h"
#import "YWMaterialStockOutDetailTableViewController.h"
//#import "YWSelectContactTableViewController.h"
#import "YWMaterialListTableViewController.h"
#import "YWMaterialDetailAndCertainHeadTableViewCell.h"
#import "YWMaterialInfoTableViewCell.h"
#import "YWNewCommentCell.h"
#import "YWQrcodeManager.h"
#import "YWScanEquipmentNotMatchVC.h"

#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UIImage+Extension.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "MBProgressHUD.h"
#import "UIView+Extension.h"

#import "YWReply.h"
#import "YWMaterial.h"
#import "YWMaterialManager.h"
#import "YWPopView.h"
#import "YWMaterialApply.h"
#import "YWMaterialStockOut.h"
#import "YWMaterialReturn.h"
#import "YWMaterial.h"
#import "YWMaterialApplyDetail.h"
#import "YWMaterialStockOutDetail.h"
#import "YWMaterialReturnDetail.h"
#import "YWHandler.h"
#import "YWReplyManager.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWObserverTableViewController.h"
#import "YWSelectAtUserTableViewController.h"
#import "Masonry.h"

#import "YWObserveTableViewCell.h"
#import "YWNewReplyTableViewCell.h"
#import "YWMeterReadingDetailRecordCell.h"

@interface YWMaterialApplyDetailTableViewController ()<YWPopViewDelegate,UITextFieldDelegate,YWSelectAtUserTableViewDelegate>{
    BOOL isHiddenKeyboard;
}
@property (nonatomic, strong) NSArray<YWReply *>* replyArray;
@property (nonatomic, strong) YWHandler *atUser;
@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, strong) NSArray * scanStockOut;

@property (nonatomic, strong) NSMutableArray * dateSource;
@property (nonatomic, strong) NSMutableArray * allMaterialArray;
@property (nonatomic, strong) YWPopView* materialPopView;
@property (nonatomic, strong) NSArray * popViewArray;
@property (nonatomic, strong) UIButton * replyButton;
@property (nonatomic, strong) UIButton * selectButton;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
/** 回复栏 */
@property (nonatomic, strong) UIView *replyView;
@end

@implementation YWMaterialApplyDetailTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"物料申请详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backToApplyView:)];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"observerIcon"] style:UIBarButtonItemStylePlain target:self action:@selector(showObservers:)];
    isHiddenKeyboard = NO;
    [self initTableView];
    [self requestApplyDetailInfo];
}

- (void)requestApplyDetailInfo{
    YWWeakSelf(weakSelf);
    [[YWMaterialManager shareManager] requestMaterialApplyWithApplyId:weakSelf.apply.applyId Complete:^(YWMaterialApply *materialApply) {
        if (materialApply) {
            YWMaterialApplyViewModel *applyViewModel = [[YWMaterialManager shareManager] materialApplyWithMaterialApplyId:materialApply.applyId];
            if (applyViewModel) {
                weakSelf.apply = applyViewModel;
                weakSelf.dateSource = nil;
                [weakSelf.tableView reloadData];
            }
        }
    }];
}

- (void)initTableView{
    [self.tableView registerClass:[YWMaterialDetailAndCertainHeadTableViewCell class] forCellReuseIdentifier:YWMaterialDetailAndCertainHeadTableViewCellIdentifier];
    [self.tableView registerClass:[YWMaterialInfoTableViewCell class] forCellReuseIdentifier:YWMaterialInfoTableViewCellIdentifier];
    [self.tableView registerClass:[YWNewCommentCell class] forCellReuseIdentifier:YWNewCommentCellIdetifer];
    [self.tableView registerClass:[YWObserveTableViewCell class] forCellReuseIdentifier:YWObserveTableViewCellIdentifier];
    [self.tableView registerClass:[YWNewReplyTableViewCell class] forCellReuseIdentifier:YWNewReplyTableViewCellIdetifer];
    [self.tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 46, 0);
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.navigationController.view addSubview:self.replyView];
}

- (NSMutableArray *)dateSource{
    if (!_dateSource) {
        NSMutableArray * dateSoure = [NSMutableArray array];
        _dateSource = dateSoure;
        [_dateSource addObjectsFromArray:self.apply.details];
    }
    return _dateSource;
}

- (NSArray *)replyArray{
    if (!_replyArray) {
        NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:self.apply.applyId andRelationType:YWReplyRelationTypeMaterialApply];
        _replyArray = commentArray;
    }
    return _replyArray;
}

- (void)addObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:self.apply.observers];
        [tempArray addObject:handler];
        self.apply.observers = [NSArray arrayWithArray:tempArray];
        _replyArray = nil;
        [self.tableView reloadData];
    }
}

- (void)deleteObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[self.apply.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:self.apply.observers];
            [tempArray removeObject:handler];
            self.apply.observers = [NSArray arrayWithArray:tempArray];
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:@"请填写回复内容"];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:@"回复内容不超过100字"];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    [[YWMaterialManager shareManager] commitMaterialReplyContent:textField.text atUser:self.atUser Type:YWReplyRelationTypeMaterialApply RelationId:self.apply.applyId WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:@"回复成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:KPostMaterialApplyReplyNotification object:nil];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            _replyArray = nil;
            [self.tableView reloadData];
            [self requestApplyDetailInfo];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return self.dateSource.count;
    }else{
        if (self.replyArray.count>0) {
            return [self.replyArray count] + 2;//参与人+“评论”
        }else{
            return 1;
        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        YWMaterialDetailAndCertainHeadTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMaterialDetailAndCertainHeadTableViewCellIdentifier];
        [self configureHeadViewCell:cell atIndexPath:indexPath];
        return cell;
    }else if(indexPath.section == 1){
        YWMaterialInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMaterialInfoTableViewCellIdentifier];
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        if (indexPath.row == 0) {
            YWObserveTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWObserveTableViewCellIdentifier];
            cell.apply = self.apply;
            return cell;
        }else{
            if (indexPath.row == 1) {
                YWMeterReadingDetailRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
                NSString *count;
                if (self.replyArray.count>0) {
                    count = [NSString stringWithFormat:@"(%ld)",(unsigned long)self.replyArray.count];
                }else{
                    count = @"";
                }
                NSString *replyText = [NSString stringWithFormat:@"评论%@:",count];
                cell.contentLabel.text = replyText;
                cell.contentLabel.textColor = [UIColor customTextGrayColor];
                return cell;
            }
            YWNewReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNewReplyTableViewCellIdetifer];
            YWReply *reply = self.replyArray[indexPath.row-2];
            cell.reply = reply;
            return cell;
        }
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (indexPath.section == 0) {
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialDetailAndCertainHeadTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialDetailAndCertainHeadTableViewCell *cell) {
//            [self configureHeadViewCell:cell atIndexPath:indexPath];
//        }];
//    }else if(indexPath.section == 1){
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialInfoTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialInfoTableViewCell *cell) {
//            [self configureCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        return [tableView fd_heightForCellWithIdentifier:YWNewCommentCellIdetifer cacheByIndexPath:indexPath configuration:^(YWNewCommentCell *cell) {
//            [self configureCommentCell:cell atIndexPath:indexPath];
//        }];
//    }
//}

- (void)configureHeadViewCell:(YWMaterialDetailAndCertainHeadTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    cell.apply = self.apply;
}

- (void)configureCell:(YWMaterialInfoTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    YWMaterialApplyDetail * applyDetail = self.dateSource[indexPath.row];
    cell.applyDetail = applyDetail;
}

- (void)configureCommentCell:(YWNewCommentCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWReply *reply = self.replyArray[indexPath.row];
    cell.reply = reply;
    //除了第一条评论则隐藏最左边评论图标
    [cell viewWithTag:101 ].hidden = indexPath.row == 0 ? NO : YES;
}

#pragma mark - table view section header view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWMaterialDetailTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2016;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 25);
    return headerView;
    
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        return @"物料申请清单";
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 25;
    }else{
        return 0.01;
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return 23;
    }else{
        return 0.01;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section!=1) {
        return nil;
    }
    static NSString* HeaderIdentifier = @"YWCirculatonDetailVCForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor whiteColor];
        //评论
        UILabel *replyLabel = [[UILabel alloc] init];
        replyLabel.textAlignment = NSTextAlignmentLeft;
        replyLabel.textColor = [UIColor customTextGrayColor];
        replyLabel.tag = 2006;
        replyLabel.font = KSmallContentFont;
        replyLabel.userInteractionEnabled = YES;
        [replyLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyLabel];
        
        UIImageView *replyImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"remind_replyIcon"]];
        replyImageView.tag = 2006;
        replyImageView.userInteractionEnabled = YES;
        [replyImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyImageView];
        
        [replyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(replyImageView.mas_top);
            make.left.mas_equalTo(replyImageView.mas_right).offset(8);
            make.right.mas_equalTo(headerView.mas_right).offset(-8);
            make.bottom.mas_equalTo(replyImageView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        //参与者
        UILabel *observerLabel = [[UILabel alloc] init];
        observerLabel.textAlignment = NSTextAlignmentLeft;
        observerLabel.textColor = [UIColor customTextGrayColor];
        observerLabel.tag = 2007;
        observerLabel.font = KSmallContentFont;
        observerLabel.userInteractionEnabled = YES;
        [observerLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerLabel];
        
        UIImageView *observerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_invite"]];
        observerView.tag = 2007;
        observerView.userInteractionEnabled = YES;
        [observerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerView];
        
        [observerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [observerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(observerView.mas_top);
            make.left.mas_equalTo(observerView.mas_right).offset(8);
            make.right.mas_equalTo(replyImageView.mas_left).offset(-8);
            make.bottom.mas_equalTo(observerView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        
    }
    UILabel* label = [headerView viewWithTag:2006];
    label.text = @"评论";
    
    //参与者
    label = [headerView viewWithTag:2007];
    label.text = @"邀请";
    return headerView;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)backToApplyView:(id)sender{
    [self.replyView removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

- (YWPopView*)materialPopView
{
    if (!_materialPopView) {
        //全局array
        YWPopView* materialPopView = [[YWPopView alloc] initReturnBackWithTitle:[NSString stringWithFormat:@"物料领用清单"] Materials:self.popViewArray type:@"领用"];
        
        materialPopView.delegate = self;
        _materialPopView = materialPopView;
    }
    return _materialPopView;
}

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    YWSelectAtUserTableViewController * selectAtUserVC = [[YWSelectAtUserTableViewController alloc] init];
    selectAtUserVC.delegate = self;
    NSMutableArray *allUser = [NSMutableArray array];
    [allUser addObjectsFromArray:self.apply.creator?@[self.apply.creator]:nil];
    [allUser addObjectsFromArray:self.apply.receivers];
    [allUser addObjectsFromArray:self.apply.observers];
    selectAtUserVC.allUserArray = allUser;
    [self.navigationController pushViewController:selectAtUserVC animated:YES];
}

- (void)handleReplyLabelTapEvent:(id)sender{
    [self.textField becomeFirstResponder];
}

- (void)handleObserverLabelTapEvent:(id)sender{
    YWObserverTableViewController *observerVC = [[YWObserverTableViewController alloc] init];
    observerVC.creaters = self.apply.creator?@[self.apply.creator]:nil;
    observerVC.executors = self.apply.receivers;
    observerVC.observers = self.apply.observers;
    observerVC.relationId = [@(self.apply.applyId) stringValue];
    observerVC.type = YWReplyRelationTypeMaterialApply;
    [self.navigationController pushViewController:observerVC animated:YES];
}


- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        _replyView.hidden = YES;
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH-40-15, 40)];
    self.textField.placeholder = @"回复";
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.delegate = self;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, 40, 40);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)selectAtUser:(YWHandler *)contact{
    if (contact) {
        isHiddenKeyboard = YES;
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

#pragma mark ----- 有关键盘
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.replyView.hidden = YES;
    [self.textField endEditing:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.replyView.hidden = NO;
    [self setUpNotification];
    if (isHiddenKeyboard) {
        [self.textField becomeFirstResponder];
        isHiddenKeyboard = NO;
    }
}

- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver:) name:KPostMissionAddObserverNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteObserver:) name:KPostMissionDeleteObserverNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT;
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.navigationController.view endEditing:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
